<template>
	<div class="m-window" v-loading="pageLoading" element-loading-text="数据加载中">
		<!--供应商提交长融申请表-->
		<el-row :gutter="10" class="header-btns-col">
			<el-col :span="2">
				<el-button type="primary" @click="backtrack">返回</el-button>
			</el-col>
			<!-- <el-col :span="2">
                <el-button type="primary" @click="saveApply">保存</el-button>
			</el-col>-->
		</el-row>
		<el-row
			:gutter="10"
			v-show="!isSubmitApplyTable && !pageLoading"
			style="margin-top:10px;"
			class="footer-btns-col"
		>
			<el-col :span="2">
				<el-button type="primary" @click="commitApply">提交</el-button>
			</el-col>
		</el-row>
		<el-row>
			<el-col :span="10">
				<table class="emphasis-table">
					<tr>
						<th>流程编号：</th>
						<td class="hit font-underline">{{applyLongTableForm.item_no}}</td>
					</tr>
					<tr>
						<th>供应商名称：</th>
						<td>{{applyLongTableForm.cust_name}}</td>
					</tr>
					<tr>
						<th>融资产品：</th>
						<td>月有钱</td>
					</tr>
					<tr>
						<th>收款账户户名：</th>
						<td>{{applyLongTableForm.cust_esign_name}}</td>
					</tr>
					<tr>
						<th>收款账户账号：</th>
						<td>{{applyLongTableForm.cust_esign_bankno}}</td>
					</tr>
					<tr>
						<th>收款账户开户行：</th>
						<td>{{applyLongTableForm.cust_esign_bank}}</td>
					</tr>
					<tr>
						<th>受理意见：</th>
						<td>{{applyLongTableForm.apply_remark}}</td>
					</tr>
					<tr>
						<th>授信额度(元)：</th>
						<td>{{applyLongTableForm.credit_line}} 元</td>
					</tr>
					<tr>
						<th>
							<div>
								<span style="color:red">*</span>
								<span>申请融资金额(元)：</span>
							</div>
						</th>
						<td v-if="!isSubmitApplyTable">
							<div class="flexs">
								<el-input
									v-model="applyLongTableForm.apply_amt"
									placeholder="输入金额"
									:readonly="isSubmitApplyTable"
									@blur="checkNum"
									@keyup.native="clearNoNum()"
								></el-input>
								<span style="line-height:36px;">元</span>
							</div>
						</td>
						<td v-else>{{applyLongTableForm.apply_amt}} 元</td>
					</tr>
					<tr>
						<th>
							<div>
								<span style="color:red">*</span>
								<span>申请融资开始日期：</span>
							</div>
						</th>
						<td v-if="!isSubmitApplyTable">
							<el-date-picker
								v-model="applyLongTableForm.apply_date"
								:picker-options="pickerOptionsBegin"
								type="date"
								placeholder="选择日期"
								:readonly="this.currentAct=='联塑金融审批'"
								@change="getSTime"
							></el-date-picker>
						</td>
						<td v-else>{{applyLongTableForm.apply_date}}</td>
					</tr>
					<tr>
						<th>
							<div>
								<span style="color:red">*</span>
								<span>申请融资到期日期：</span>
							</div>
						</th>
						<td v-if="!isSubmitApplyTable">
							<el-date-picker
								v-model="applyLongTableForm.prepayback_date"
								:picker-options="pickerOptionsEnd"
								type="date"
								placeholder="选择日期"
								:readonly="this.currentAct=='联塑金融审批'"
								@change="getETime"
							></el-date-picker>
						</td>
						<td v-else>{{applyLongTableForm.prepayback_date}}</td>
					</tr>
					<tr>
						<th>申请融资天数：</th>
						<td>{{getDayAmount}}</td>
					</tr>
					<tr>
						<th>服务费率（不含税）：</th>
						<td>{{serviceRate}}</td>
					</tr>
					<tr>
						<th>利率（不含税）：</th>
						<td>{{showRate}}</td>
					</tr>
					<tr>
						<th>服务费（不含税）(元)：</th>
						<td>{{getServiceFee}}</td>
					</tr>
					<tr>
						<th>利息（不含税）(元)：</th>
						<td>{{getNumberRate}}</td>
					</tr>
					<tr>
						<th>应还款金额(元)：</th>
						<td>{{applyLongTableForm.apply_amt}}</td>
					</tr>
					<tr>
						<th>金融客服：</th>
						<td>{{applyLongTableForm.apply_user}}</td>
					</tr>
					<tr>
						<th>客服电话：</th>
						<td>{{applyLongTableForm.apply_phone}}</td>
					</tr>
				</table>
			</el-col>
		</el-row>
		<el-row v-show="returnReason!=''">
			<el-col :span="23">
				<label style="color:red;">退回原因</label>
				<div class="returnReason">{{returnReason}}</div>
			</el-col>
		</el-row>
	</div>
</template>
<style lang="less" rel="stylesheet/less" scoped>
.m-window {
	padding: 50px 0;
	overflow: auto;
	overflow-x: hidden;

	.footer-btns-col,
	.header-btns-col {
		position: fixed;
		height: 60px;
		width: 100%;
		bottom: 0;
		z-index: 10;
		margin-left: -11px !important;
		box-sizing: border-box;
		display: flex;
		justify-content: center;
		align-items: center;
		background: #fff;
		padding: 10px 0;
		border-top: 1px solid #eee;

		/deep/ .el-button {
			margin-left: -84px;
		}
	}

	.header-btns-col {
		top: 0;
		justify-content: flex-start;
		border-top: none;
		border-bottom: 1px solid #eee;
		margin-top: 100px;

		/deep/ .el-button {
			margin-left: 8px;
		}
	}
}

.emphasis-table {
	width: 100%;
	height: 100%;
	margin-top: 10px;

	td,
	th {
		border: 1px solid #eee;
		padding: 0 10px;
		height: 38px;
		width: 50%;
		text-align: right;
	}

	& tr:nth-child(even) th,
	& tr:nth-child(even) td {
		background: #f9fafa;
	}

	.font-underline {
		text-decoration: underline;
	}

	.hit {
		color: #409eff !important;
	}

	td {
		text-align: left;

		& /deep/.el-input {
			width: 80%;

			.el-input__inner {
				border: none !important;
				outline-style: none !important;
				height: 35px;
				line-height: 35px;
				margin-left: -10px;
				font-size: 14px;
			}

			.el-input__icon {
				margin-left: -10px;
				margin-top: -2px;
			}
		}
	}
}

.footer-btns-col,
.header-btns-col {
	position: fixed;
	height: 60px;
	width: 100%;
	bottom: 0;
	z-index: 10;
	margin-left: -11px !important;
	box-sizing: border-box;
	display: flex;
	justify-content: center;
	align-items: center;
	background: #fff;
	padding: 10px 0;
	border-top: 1px solid #eee;

	/deep/ .el-button {
		margin-left: -84px;
	}
}

.header-btns-col {
	top: 0;
	justify-content: flex-start;
	border-top: none;
	border-bottom: 1px solid #eee;
	margin-top: 100px;

	/deep/ .el-button {
		margin-left: 8px;
	}
}
</style>
<style>
.flexs {
	display: flex !important;
	overflow: hidden !important;
}

.flexs span {
	line-height: 1;
}

.returnReason {
	border: 1px solid #eee;
	padding: 5px;
	min-height: 100px;
	margin-top: 5px;
}
</style>

<script>
import {
	numberDiv,
	formatPrice,
	formatPriceEdit,
	regainOriginalMoneyFormat,
	formatRate,
	dateDiff,
	getSpecifyDate,
	numberMul,
	numberSub
} from '@/util/format'
// import { dateDiff } from "@/util/format.js"
import {
	mapState,
	mapActions
} from 'vuex'
export default {
	props: {
		currentAct: String,
		applyListApplyId: String
	},
	data () {
		return {
			pageLoading: true,
			applyLongTableForm: {
				id: "",
				item_no: "",
				cust_name: "",
				apply_amt: 0,
				moneyReaadOnly: false,
				apply_date: "",
				prepayback_date: "",
				apply_user: "",
				apply_phone: "",
				cust_esign_bank: "",
				cust_esign_bankno: "",
				cust_esign_name: "",
				service_rate: "",
				rate: "",
				apply_remark: "",
				credit_line: "",
				value: ""
			},
			getNumberRate: "",
			getServiceFee: "",
			returnReason: ""
		};
	},
	created () { },
	beforeMount () {
		// this.applyListApplyId;
		if (!this.applyListApplyId) {
			this.$alert("获取申请信息失败", {
				confirmButtonText: "确定",
				customClass: "alertFailure"
			});
			return;
		}
		if (this.currentAct == '已退回') {
			this.getRefusedActivity(this.applyListApplyId)
		}
		this.getApplyInfo()
		this.getDays()
	},
	computed: {
		...mapState([
			'supplyChainFinance', 'supplierApplyList'
		]),
		getDayAmount () {
			let beginDate = this.applyLongTableForm.payDate ? this.applyLongTableForm.payDate : this.applyLongTableForm.apply_date
			let endDate = this.applyLongTableForm.paybackDate ? this.applyLongTableForm.paybackDate : this.applyLongTableForm.prepayback_date
			let applyDay = dateDiff(
				beginDate,
				endDate
			);
			if (applyDay > 0) {
				applyDay = applyDay - 1
			}
			this.applyLongTableForm.dayAmount = applyDay
			return applyDay + "天";
		},
		isSubmitApplyTable () {
			return this.currentAct == '联塑金融审批' || this.currentAct == '已结束' || this.currentAct == '已退回' || this.currentAct ==
				'已完成'
		},
		//显示利率
		serviceRate () {
			return formatRate(this.applyLongTableForm.service_rate) + "/年";
		},
		//显示利率
		showRate () {
			return formatRate(this.applyLongTableForm.rate) + "/年";
		},
		// getNumberRate(){
		//   let applyAmt = regainOriginalMoneyFormat(this.applyLongTableForm.apply_amt)//去除千分位
		//   let preDeductAmount
		//   let numberss =numberMul(numberMul(applyAmt,this.applyLongTableForm.rate),this.applyLongTableForm.dayAmount);
		//   let num
		//   if(numberss){
		//     num=numberss.toFixed(2); 
		//   }
		//    preDeductAmount = numberDiv(num,360)
		//    return formatPrice(preDeductAmount)+'元';
		// },
		// getServiceFee(){
		//   let applyAmt = regainOriginalMoneyFormat(this.applyLongTableForm.apply_amt)//去除千分位
		//   let preDeductAmount
		//   let numberss =numberMul(numberMul(applyAmt,this.applyLongTableForm.service_rate),this.applyLongTableForm.dayAmount)
		//   let num 
		//   if(numberss){
		//     num=numberss.toFixed(2); 
		//   }
		//    preDeductAmount = numberDiv(num,360)
		//    return formatPrice(preDeductAmount)+'元';
		// },
		pickerOptionsBegin () {
			let dateFormat = this.$utils.dateFormat
			let prepaybackDate = this.applyLongTableForm.prepayback_date //取结束日期时间
			//大于当前月25号 的日期不可选
			// let lastDay = getSpecifyDate(25)
			let that = this
			return {
				disabledDate (time) {
					//开始日期不可大于融资到期日期 并且 开始日期不可大于当前日期
					if (prepaybackDate && time.getTime() > prepaybackDate || time < new Date()) {
						return true
					}
					return that.datePickerOptions(time, dateFormat('yyyy-MM-dd', time), true)
				}
			}
		},
		pickerOptionsEnd () {
			let dateFormat = this.$utils.dateFormat
			let beginTime = this.applyLongTableForm.apply_date //取开始日期时间
			let that = this
			let date = new Date(beginTime);
			let time1 = date.getTime();
			return {
				disabledDate (time) {
					if (time1 && time1 >= time.getTime()) {
						return true
					}
					return that.datePickerOptions(time, dateFormat('yyyy-MM-dd', time))
				}
			}
		}


	},
	methods: {
		...mapActions([
			'changeTOdo',
			'changePageCode'
		]),
		getRefusedActivity (applyId) {
			this.$http.getRefusedActivity({
				applyId: applyId
			}).then(({
				data
			}) => {
				if (data.code == 200 && data.rows) {
					this.returnReason = data.rows.note || ''
				}
			}).catch(error => {
				this.$alert("查询退回信息数据失败，请检查网络！", {
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				});
			})
		},
		commitApply () {
			let money = regainOriginalMoneyFormat(this.applyLongTableForm.apply_amt)
			let creditLine = regainOriginalMoneyFormat(this.applyLongTableForm.credit_line)
			if (!money) {
				this.$alert("请输入申请融资金额", {
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				});
				return;
			}
			if (money < 10000) {
				this.$alert("申请融资金额不得小于一万元", {
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				});
				this.applyLongTableForm.apply_amt = ''
				return;
			}
			if (Number(money) > Number(creditLine)) {
				this.$alert("申请融资金额不得大于授信额度", {
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				});
				return;
			}
			if (!this.applyLongTableForm.apply_date) {
				this.$alert("请选择联塑金融融资开始日期", {
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				});
				return;
			}
			if (!this.applyLongTableForm.prepayback_date) {
				this.$alert("请选择联塑金融融资到期日期", {
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				});
				return;
			}
			if (this.applyLongTableForm.apply_date == this.applyLongTableForm.prepayback_date) {
				this.applyLongTableForm.prepayback_date = ''
				this.$alert("融资开始日期与融资到期日期不能为同一天", {
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				});
				return;
			}

			let applyDay = dateDiff(this.applyLongTableForm.apply_date, this.applyLongTableForm.prepayback_date) - 1
			if (applyDay < 31) {
				this.$alert("“月有钱”产品最小融资天数为31天，请重新选择融资开始日期或到期日期", {
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				});
				return;
			}
			if (applyDay > 186) {
				this.$alert("“月有钱”产品最大融资天数为186天，请重新选择融资开始日期或到期日期", {
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				});
				return;
			}
			// if (getDayAmount<=30) {
			//   this.$message.error("融资期限不得低于一个月");
			//   return;
			// } 

			const loading = this.$loading({
				lock: true,
				text: "融资申请提交中，请稍等",
				spinner: "el-icon-loading",
				background: "rgba(255,255,255,.9)"
			});
			let params = new Object();
			let apply_date = this.applyLongTableForm.apply_date
			let prepayback_date = this.applyLongTableForm.prepayback_date
			params = {
				id: this.applyLongTableForm.id,
				applyAmt: money,
				applyDate: (typeof (apply_date) == "object") ? Date.parse(apply_date) : apply_date,
				prepaybackDate: (typeof (prepayback_date) == "object") ? Date.parse(prepayback_date) : prepayback_date
			};
			this.$http.submitApply(params).then(response1 => {
				let that = this
				setTimeout(() => {
					loading.close()
					if (response1.data.code == 200) {
						this.$alert("提交成功", {
							confirmButtonText: "确定",
							customClass: "alertSuccess"
						});
						that.isSign = true;
						that.applyId = that.applyLongTableForm.id;
						that.changePageCode('')
					} else {
						this.$alert(response1.data.info, {
							confirmButtonText: "确定",
							customClass: "alertFailure"
						});
					}
				}, 500)
			})
				.catch(errror => {
					loading.close()
					this.$alert("提交失败，请检查网络！", {
						confirmButtonText: "确定",
						customClass: "alertFailure"
					});
				});

		},
		backtrack () {
			this.changePageCode('')
		},
		changeMoney () {
			this.getNumberRate = this.countRate(this.applyLongTableForm.rate)
			this.getServiceFee = this.countRate(this.applyLongTableForm.service_rate)
		},
		getApplyInfo () {
			let that = this
			this.$http.getApplyInfo({
				id: this.applyListApplyId
			}).then(response => {
				setTimeout(() => {
					that.pageLoading = false
				}, 500)
				if (response.data.code == 200) {
					let data = response.data.rows;
					this.applyLongTableForm.id = data.id;
					this.applyLongTableForm.item_no = data.itemNo;
					this.applyLongTableForm.cust_name = data.custName;
					this.applyLongTableForm.apply_user = data.applyUser;
					this.applyLongTableForm.apply_phone = data.applyPhone;
					this.applyLongTableForm.cust_esign_bank = data.custEsignBank;
					this.applyLongTableForm.cust_esign_bankno = data.custEsignBankno;
					this.applyLongTableForm.apply_amt = data.actAmt ? formatPrice(data.actAmt) : formatPrice(data.applyAmt);
					this.applyLongTableForm.cust_esign_name = data.custEsignName;
					this.applyLongTableForm.service_rate = data.serviceRate;
					this.applyLongTableForm.rate = data.rate;
					this.applyLongTableForm.rate = data.rate;
					this.applyLongTableForm.apply_remark = data.applyRemark;
					this.applyLongTableForm.credit_line = formatPrice(data.creditLine);
					let dd = new Date(new Date().toLocaleDateString());
					this.applyLongTableForm.apply_date = data.applyDate ? data.applyDate.substring(0, 10) : "";
					this.applyLongTableForm.prepayback_date = data.prepaybackDate ? data.prepaybackDate.substring(0, 10) : "";
					this.applyLongTableForm.payDate = data.payDate ? data.payDate.substring(0, 10) : "";
					this.applyLongTableForm.paybackDate = data.paybackDate ? data.paybackDate.substring(0, 10) : "";
					let beginDate = this.applyLongTableForm.payDate ? this.applyLongTableForm.payDate : this.applyLongTableForm.apply_date
					let endDate = this.applyLongTableForm.paybackDate ? this.applyLongTableForm.paybackDate : this.applyLongTableForm.prepayback_date

					this.applyLongTableForm.apply_date = beginDate
					this.applyLongTableForm.prepayback_date = endDate
					let applyDay = that.dateBet(beginDate, endDate)
					if (applyDay > 0) {
						applyDay = applyDay - 1
					}
					this.applyLongTableForm.dayAmount = applyDay;
					this.getNumberRate = that.countRate(data.rate)
					this.getServiceFee = that.countRate(data.serviceRate)
				} else {
					this.$alert("获取申请主表信息失败，请检查网络！", {
						confirmButtonText: "确定",
						customClass: "alertFailure"
					});
				}
			})
				.catch(errror => {
					this.pageLoading = false
					this.$alert("查询对账列表失败，请检查网络！", {
						confirmButtonText: "确定",
						customClass: "alertFailure"
					});
				});
		},
		datePickerOptions (time, dateStr, isBeginDate) {
			let weeks = time.getDay() //周几？
			let day = time.getDate() //几号？
			// if (isBeginDate && day < 5 || day > 25) {
			//     return false
			// }
			if (this.whitelist.includes(dateStr)) {
				return false
			}
			if (this.blacklist.includes(dateStr) || weeks == 6 || weeks == 0) {
				return true
			}
			return false
		},
		async getDays () {
			let that = this
			await this.$http.getDays().then(({
				data
			}) => {
				if (data.code == 200 && data.rows) {
					that.whitelist = data.rows.workdays
					that.blacklist = data.rows.holidays
				} else {
					this.$alert(`获取数据失败：${data.info}`, {
						confirmButtonText: "确定",
						customClass: "alertFailure"
					})
				}
			}).catch(error => {
				this.$alert("查询失败，请检查网络！", {
					confirmButtonText: "确定",
					customClass: "alertFailure"
				})
			})
		},
		//开始日期选中事件
		getSTime () {
			this.getNumberRate = this.countRate(this.applyLongTableForm.rate)
			this.getServiceFee = this.countRate(this.applyLongTableForm.service_rate)
		},
		//结束日期选中事件
		getETime () {
			this.getNumberRate = this.countRate(this.applyLongTableForm.rate)
			this.getServiceFee = this.countRate(this.applyLongTableForm.service_rate)
		},
		// //金额输入时计算利率
		// getValue(){
		//   this.countRate(this.applyLongTableForm.rate);
		//   this.countRate(this.applyLongTableForm.service_rate);
		// },
		//计算费率事件
		countRate (rateData) {
			let applyAmt = Number(regainOriginalMoneyFormat(this.applyLongTableForm.apply_amt))
			let numberss = ((applyAmt * rateData / 360) * this.applyLongTableForm.dayAmount).toFixed(2)
			return formatPrice(numberss);
		},
		dateBet (sDate1, sDate2) {
			if (!sDate1 || !sDate2) {
				return 0
			}
			let dateSpan, iDays;
			sDate1 = !isNaN(sDate1) ? sDate1 : Date.parse(sDate1);
			sDate2 = !isNaN(sDate2) ? sDate2 : Date.parse(sDate2);
			dateSpan = sDate2 - sDate1;
			dateSpan = Math.abs(dateSpan);
			iDays = Math.floor(dateSpan / (24 * 3600 * 1000));
			return parseInt(iDays) + 1
		},
		checkNum () {
			this.applyLongTableForm.value = regainOriginalMoneyFormat(this.applyLongTableForm.apply_amt)
			const nums = this.applyLongTableForm.apply_amt.toString().split('.')
			if (nums.length == 1) {
				this.applyLongTableForm.apply_amt = this.applyLongTableForm.apply_amt + '.00'
			} else if (nums[1].length == 1) {
				this.applyLongTableForm.apply_amt = this.applyLongTableForm.apply_amt + '0'
			}
			if (this.applyLongTableForm.value && this.applyLongTableForm.value < 10000) {
				this.$alert("申请融资金额不得小于一万元", {
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				});
				this.applyLongTableForm.apply_amt = '';
				return false
			}
		},
		//只允许输入两位小数，并实时转换为千分位
		clearNoNum () {
			// if(typeof  this.applyLongTableForm.apply_amt=='string'){ 
			//     this.applyLongTableForm.apply_amt = this.applyLongTableForm.apply_amt.replace(/[^(\d|.)]/g,"");
			//     this.applyLongTableForm.apply_amt = this.applyLongTableForm.apply_amt.replace(/\.{2,}/g,"."); //只保留第一个. 清除多余的   
			//     this.applyLongTableForm.apply_amt = this.applyLongTableForm.apply_amt.replace(".","$#$").replace(/\./g,"").replace("$#$",".");  
			//     this.applyLongTableForm.apply_amt = this.applyLongTableForm.apply_amt.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');//只能输入两个小数   
			//     if(this.applyLongTableForm.apply_amt.indexOf(".")< 0 && this.applyLongTableForm.apply_amt !=""){//以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额  
			//         this.applyLongTableForm.apply_amt= parseFloat(this.applyLongTableForm.apply_amt);  
			//     }
			// }
			if (typeof this.applyLongTableForm.apply_amt == 'string') {
				this.applyLongTableForm.apply_amt = this.applyLongTableForm.apply_amt.replace(/[^(\d|.)]/g, "");
				this.applyLongTableForm.apply_amt = this.applyLongTableForm.apply_amt.replace(/\.{2,}/g,
					"."); //只保留第一个. 清除多余的   
				this.applyLongTableForm.apply_amt = this.applyLongTableForm.apply_amt.replace(".", "$#$").replace(/\./g, "")
					.replace("$#$", ".");
				this.applyLongTableForm.apply_amt = this.applyLongTableForm.apply_amt.replace(/^(\-)*(\d+)\.(\d\d).*$/,
					'$1$2.$3'); //只能输入两个小数   
				this.applyLongTableForm.apply_amt = formatPriceEdit(this.applyLongTableForm.apply_amt.toString().replace(
					/[,]/g, ''))
			}
			this.changeMoney()
		},
	}
};
</script>